from contextlib import contextmanager
import io
import time


@contextmanager
def my_open(path) -> io.TextIOBase:
    print(f'Opening {path}')
    f = open(path, 'r', encoding='utf8')
    print(f'Opened {path}')
    yield f
    print(f'Closing {path}')
    f.close()
    print(f'Closed {path}')


if __name__ == '__main__':

    def main():
        path = r'D:\_dell7590_root\local\LNP_datasets\med\med_dialog\MedDialog_processed\MedDialog_processed\train_data.json'

        with my_open(path) as f:
            if 1:
                for i in range(4):
                    n = i + 1
                    line = f.readline()
                    print(n, line)
            else:
                """
                Experiment effect is not as expected.
                So, opened file is just a pointer not a content.
                """
                print('Fetching all ...')
                if 0:
                    for i in range(4):
                        n = i + 1
                        print(f'No.{n}')
                        lines = f.readlines()
                        print(f'Fetched {len(lines):,d} characters')
                        del lines
                else:
                    f.readlines()

        n_sleep = 600
        print(f'Sleep for {n_sleep} seconds ...')
        time.sleep(n_sleep)

    main()
